/**
 * Thinking Chain Viewer
 * 
 * 思维链查看器 - 主容器组件
 */

import * as React from 'react';
import { ChevronDown, ChevronUp, Download, Settings, Brain, Clock, List } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { ThinkingTimeline } from './ThinkingTimeline';
import type { ThinkingChain, ThinkingVisualizationConfig } from '@/types/thinking';
import { generateThinkingSummary } from '@/lib/thinking-parser';
import { cn } from '@/lib/utils';

export interface ThinkingChainViewerProps {
  /** 思维链数据 */
  chain: ThinkingChain;
  /** 可视化配置 */
  config?: Partial<ThinkingVisualizationConfig>;
  /** 默认是否展开 */
  defaultExpanded?: boolean;
  /** 类名 */
  className?: string;
}

/**
 * 默认配置
 */
const DEFAULT_CONFIG: ThinkingVisualizationConfig = {
  showTimeline: true,
  showDuration: true,
  showConfidence: false,
  showToolCalls: true,
  autoExpand: false,
  animationSpeed: 300,
  theme: 'auto',
};

/**
 * 思维链查看器组件
 */
export function ThinkingChainViewer({
  chain,
  config: userConfig,
  defaultExpanded = false,
  className,
}: ThinkingChainViewerProps) {
  const [isExpanded, setIsExpanded] = React.useState(defaultExpanded);
  const config = React.useMemo(
    () => ({ ...DEFAULT_CONFIG, ...userConfig }),
    [userConfig]
  );

  // 生成摘要（如果没有）
  const summary = React.useMemo(() => {
    return chain.summary || generateThinkingSummary(chain);
  }, [chain]);

  // 导出思维链（简化版）
  const handleExport = React.useCallback(() => {
    const markdown = exportToMarkdown(chain);
    const blob = new Blob([markdown], { type: 'text/markdown' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `thinking-chain-${chain.id}.md`;
    a.click();
    URL.revokeObjectURL(url);
  }, [chain]);

  // 格式化总耗时
  const formatDuration = React.useCallback(() => {
    const seconds = chain.totalDuration / 1000;
    if (seconds < 1) return `${chain.totalDuration}ms`;
    if (seconds < 60) return `${seconds.toFixed(1)}s`;
    const minutes = Math.floor(seconds / 60);
    const remainingSeconds = Math.floor(seconds % 60);
    return `${minutes}m ${remainingSeconds}s`;
  }, [chain.totalDuration]);

  return (
    <div
      className={cn(
        'thinking-chain-viewer',
        'border rounded-lg overflow-hidden',
        'bg-card text-card-foreground',
        'transition-all duration-200',
        className
      )}
    >
      {/* 折叠状态 - 简洁摘要 */}
      {!isExpanded && (
        <div
          className={cn(
            'flex items-center justify-between p-3',
            'cursor-pointer hover:bg-muted/50 transition-all',
            'group'
          )}
          onClick={() => setIsExpanded(true)}
        >
          <div className="flex items-center gap-3 flex-1 min-w-0">
            {/* 图标 */}
            <div className="shrink-0 p-2 rounded-lg bg-primary/10 group-hover:bg-primary/20 transition-colors">
              <Brain className="w-4 h-4 text-primary" />
            </div>
            
            {/* 摘要信息 */}
            <div className="flex items-center gap-2 flex-wrap flex-1 min-w-0">
              <span className="text-sm font-medium">思考了</span>
              <Badge variant="secondary" className="font-mono">
                <List className="w-3 h-3 mr-1" />
                {chain.steps.length} 步
              </Badge>
              <Badge variant="outline" className="font-mono">
                <Clock className="w-3 h-3 mr-1" />
                {formatDuration()}
              </Badge>
            </div>
          </div>

          {/* 展开按钮 */}
          <Button
            variant="ghost"
            size="sm"
            className="shrink-0 text-xs opacity-70 group-hover:opacity-100 transition-opacity"
          >
            查看详情
            <ChevronDown className="ml-1 h-3 w-3" />
          </Button>
        </div>
      )}

      {/* 展开状态 - 完整内容 */}
      {isExpanded && (
        <>
          {/* 头部 */}
          <div
            className={cn(
              'flex items-center justify-between p-3',
              'border-b bg-muted/30 cursor-pointer',
              'hover:bg-muted/50 transition-colors'
            )}
            onClick={() => setIsExpanded(false)}
          >
            <div className="flex items-center gap-3">
              <div className="p-2 rounded-lg bg-primary/10">
                <Brain className="w-4 h-4 text-primary" />
              </div>
              <div>
                <div className="text-sm font-semibold">思维过程</div>
                <div className="text-xs text-muted-foreground">
                  {chain.steps.length} 个步骤 • {formatDuration()}
                </div>
              </div>
            </div>

            <div className="flex items-center gap-1">
              <Button
                variant="ghost"
                size="icon"
                className="h-7 w-7"
                onClick={(e) => {
                  e.stopPropagation();
                  handleExport();
                }}
                title="导出思维链"
              >
                <Download className="h-4 w-4" />
              </Button>
              <Button
                variant="ghost"
                size="icon"
                className="h-7 w-7"
              >
                <ChevronUp className="h-4 w-4" />
              </Button>
            </div>
          </div>

          {/* 内容 - 时间线 */}
          <div className="p-4">
            <ThinkingTimeline
              chain={chain}
              showDuration={config.showDuration}
              showConfidence={config.showConfidence}
              enableAnimation={true}
            />
          </div>
        </>
      )}
    </div>
  );
}

/**
 * 导出思维链为 Markdown
 */
function exportToMarkdown(chain: ThinkingChain): string {
  const lines: string[] = [];

  lines.push(`# 思维链 - ${chain.id}`);
  lines.push('');
  lines.push(`**开始时间**: ${chain.startTime.toLocaleString()}`);
  lines.push(`**总耗时**: ${(chain.totalDuration / 1000).toFixed(1)}s`);
  lines.push(`**步骤数量**: ${chain.steps.length}`);
  lines.push('');

  if (chain.summary) {
    lines.push(`**摘要**: ${chain.summary}`);
    lines.push('');
  }

  lines.push('## 思维步骤');
  lines.push('');

  chain.steps.forEach((step, index) => {
    lines.push(`### ${index + 1}. ${step.title}`);
    lines.push('');
    lines.push(`**类型**: ${step.type}`);
    if (step.duration) {
      lines.push(`**耗时**: ${(step.duration / 1000).toFixed(1)}s`);
    }
    if (step.tool) {
      lines.push(`**工具**: ${step.tool.name}`);
    }
    lines.push('');
    lines.push(step.content);
    lines.push('');
  });

  return lines.join('\n');
}

